package org.or5e.oss.core.api.bm.server;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;

import org.or5e.oss.core.BaseObject;

public abstract class SMTPServer extends BaseObject implements Serializable {
	private String serverName;
	private final String SMTP_HOST_NAME;
	private final String SMTP_AUTH_USER;
	private final String SMTP_AUTH_PWD;
	private final Boolean authentication;
	protected final Session mailSession;

	public SMTPServer(String hostName) {
		this(hostName, "", "", Boolean.FALSE);
	}

	public SMTPServer(String hostName, String userName, String passWd, Boolean authentication) {
		this.serverName = "Dummy";
		this.SMTP_HOST_NAME = hostName;
		this.SMTP_AUTH_USER = userName;
		this.SMTP_AUTH_PWD = passWd;
		this.authentication = authentication;
		this.mailSession = intitilizeSession();
	}
	
	private Session intitilizeSession() {
	    boolean debug = this.authentication;

	    Properties props = new Properties();
	    props.put("mail.smtp.host", SMTP_HOST_NAME);
	    props.put("mail.smtp.auth", debug);
	    Session session = null;

	    if(debug) {
		    Authenticator auth = new SMTPAuthenticator();
		    session = Session.getDefaultInstance(props, auth);
	    }
	    else {
	    	session = Session.getDefaultInstance(props, null);
	    }
	    session.setDebug(debug);
	    return session;
	}

	public abstract boolean sendMail(HashMap<String, String> header, String sender,
			String replyTo, String receipt, String subject, String message);
	

	public abstract boolean sendMail(HashMap<String, String> header, String sender,
			String receipt, String subject, String message);

	public abstract boolean sendMail(String sender, String receipt, String subject,
			String message);

	public abstract boolean sendMail(String sender, String replyTo, String receipt,
			String subject, String message) ;

	private class SMTPAuthenticator extends javax.mail.Authenticator
	{

	    public PasswordAuthentication getPasswordAuthentication()
	    {
	        String username = SMTP_AUTH_USER;
	        String password = SMTP_AUTH_PWD;
	        return new PasswordAuthentication(username, password);
	    }
	}
	public final String getServerName() {
		return serverName;
	}

	public final void setServerName(String serverName) {
		this.serverName = serverName;
	}

	@Override
	public String getName() {
		return "SMTPServer";
	}
}